import React, { useEffect, useState } from 'react'
import { 
  Table, 
  Button, 
  Space, 
  Input, 
  Select, 
  Tag, 
  Modal, 
  Form, 
  Popconfirm,
  Card,
  Row,
  Col,
  Avatar,
  Divider,
  message,
  Tooltip,
  Dropdown,
  Menu,
  Typography
} from 'antd'
import { 
  PlusOutlined, 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined,
  ReloadOutlined,
  TeamOutlined,
  UserOutlined,
  SafetyOutlined,
  DownOutlined,
  ClearOutlined,
  ExportOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { getUserList, createUser, updateUser, deleteUser } from '@/store/slices/userSlice'
import { User, UserQuery, CreateUserRequest, Role } from '@/types/user'
import roleService from '@/services/role'
import userService from '@/services/user'
import styles from './index.module.css'

const { Option } = Select
const { Text } = Typography

const UserManagement: React.FC = () => {
  const dispatch = useDispatch()
  const { users, total, loading } = useSelector((state: RootState) => state.user)
  
  const [searchForm] = Form.useForm()
  const [userForm] = Form.useForm()
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  
  // 角色相关状态
  const [roles, setRoles] = useState<Role[]>([])
  const [roleModalVisible, setRoleModalVisible] = useState(false)
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([])
  const [roleLoading, setRoleLoading] = useState(false)

  // 表格筛选相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [filteredInfo, setFilteredInfo] = useState<Record<string, string[] | null>>({})
  const [sortedInfo, setSortedInfo] = useState<Record<string, any>>({})
  const [tableLoading, setTableLoading] = useState(false)

  // 角色分配表格相关状态
  const [roleTableData, setRoleTableData] = useState<Role[]>([])
  const [roleTableLoading, setRoleTableLoading] = useState(false)
  const [roleTablePagination, setRoleTablePagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const [roleSearchParams, setRoleSearchParams] = useState<{
    roleName?: string
    status?: number
  }>({})

  // 搜索防抖
  const [searchTimeout, setSearchTimeout] = useState<NodeJS.Timeout | null>(null)

  // 加载用户列表
  const loadUsers = async (params?: UserQuery) => {
    const queryParams = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...params,
    }
    
    try {
      await dispatch(getUserList(queryParams) as any).unwrap()
      // total会通过Redux store自动更新，无需手动设置
    } catch (error) {
      // 错误已在slice中处理
    }
  }

  // 加载角色列表
  const loadRoles = async () => {
    try {
      const response = await roleService.getRoles()
      if (response.code === 200) {
        setRoles(response.data)
      }
    } catch (error) {
      console.error('加载角色列表失败:', error)
    }
  }

  // 初始化加载用户列表
  // 监听total变化，更新分页信息
  useEffect(() => {
    setPagination(prev => ({ ...prev, total }))
  }, [total])

  // 初始化加载用户列表
  useEffect(() => {
     loadUsers()
     loadRoles()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  // 当角色数据变化时，更新角色表格数据
  useEffect(() => {
    if (roles.length > 0 && roleModalVisible) {
      setRoleTableData([...roles])
      setRoleTablePagination(prev => ({
        ...prev,
        total: roles.length
      }))
    }
  }, [roles, roleModalVisible])

  // 清理搜索定时器
  useEffect(() => {
    return () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
    }
  }, [searchTimeout])

  // 搜索处理函数
  const handleSearch = (values: UserQuery) => {
    // 重置到第一页并执行搜索
    const newPagination = { ...pagination, current: 1 }
    setPagination(newPagination)
    
    // 使用新的分页参数进行搜索
    const queryParams = {
      pageIndex: 1,
      pageSize: newPagination.pageSize,
      ...values,
    }
    
    dispatch(getUserList(queryParams) as any)
  }

  // 重置搜索表单
  const handleReset = () => {
    searchForm.resetFields()
    const newPagination = { ...pagination, current: 1 }
    setPagination(newPagination)
    
    // 重置后重新加载数据
    const queryParams = {
      pageIndex: 1,
      pageSize: newPagination.pageSize,
    }
    
    dispatch(getUserList(queryParams) as any)
  }

  // 显示用户模态框
  const showUserModal = (user?: User) => {
    setEditingUser(user || null)
    setIsModalVisible(true)
    
    if (user) {
      userForm.setFieldsValue(user)
    } else {
      userForm.resetFields()
    }
  }

  // 关闭模态框
  const handleModalCancel = () => {
    setIsModalVisible(false)
    setEditingUser(null)
    userForm.resetFields()
  }

  // 保存用户信息
  const handleUserSave = async (values: Partial<User & { password: string }>) => {
    try {
      if (editingUser) {
        // 更新现有用户
        await dispatch(updateUser({ id: editingUser.id, userData: values }) as any).unwrap()
      } else {
        // 创建新用户 - 确保必需字段存在
        const userData: CreateUserRequest = {
          userName: values.userName!,
          password: values.password!,
          status: values.status ?? 1,
          realName: values.realName,
          email: values.email,
          phone: values.phone,
          remark: values.remark
        }
        await dispatch(createUser(userData) as any).unwrap()
      }
      
      // 关闭模态框并重置表单
      setIsModalVisible(false)
      setEditingUser(null)
      userForm.resetFields()
      
      // 重新加载用户列表
      await loadUsers()
    } catch (error) {
      // 错误已在slice中处理
    }
  }

  // 删除用户
  const handleUserDelete = async (id: number) => {
    try {
      await dispatch(deleteUser(id) as any).unwrap()
      // 删除成功后重新加载列表
      await loadUsers()
    } catch (error) {
      // 错误已在slice中处理
    }
  }

  // 显示角色分配模态框
  const showRoleModal = async (user: User) => {
    setSelectedUser(user)
    setRoleModalVisible(true)
    setRoleLoading(true)
    
    try {
      // 获取用户当前的角色
      const response = await userService.getUserRoles(user.id)
      if (response.code === 200) {
        const roleIds = response.data.map((role: Role) => role.id)
        setSelectedRoleIds(roleIds)
      }
      
      // 初始化角色表格数据
      await loadRoleTableData()
    } catch (error) {
      console.error('获取用户角色失败:', error)
      setSelectedRoleIds([])
    } finally {
      setRoleLoading(false)
    }
  }

  // 防抖搜索角色
  const debouncedRoleSearch = (searchParams: any) => {
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }
    
    const timeout = setTimeout(() => {
      loadRoleTableData(searchParams)
    }, 300) // 300ms防抖
    
    setSearchTimeout(timeout)
  }

  // 加载角色表格数据
  const loadRoleTableData = async (searchParams?: any) => {
    setRoleTableLoading(true)
    try {
      // 确保roles数据已加载
      if (roles.length === 0) {
        await loadRoles()
      }
      
      // 应用筛选条件
      let filteredRoles = [...roles]
      
      if (searchParams?.roleName) {
        const searchValue = searchParams.roleName.toLowerCase()
        filteredRoles = filteredRoles.filter(role => 
          role.roleName.toLowerCase().includes(searchValue) ||
          role.roleCode.toLowerCase().includes(searchValue)
        )
      }
      if (searchParams?.status !== undefined) {
        filteredRoles = filteredRoles.filter(role => role.status === searchParams.status)
      }
      
      setRoleTableData(filteredRoles)
      setRoleTablePagination(prev => ({
        ...prev,
        total: filteredRoles.length
      }))
    } catch (error) {
      console.error('加载角色表格数据失败:', error)
    } finally {
      setRoleTableLoading(false)
    }
  }


  // 保存角色分配
  const handleRoleSave = async () => {
    if (!selectedUser) return
    
    setRoleLoading(true)
    try {
      const response = await userService.assignUserRoles({
        userId: selectedUser.id,
        roleIds: selectedRoleIds
      })
      
      if (response.code === 200) {
        Modal.success({
          title: '成功',
          content: '角色分配成功'
        })
        setRoleModalVisible(false)
        setSelectedUser(null)
        setSelectedRoleIds([])
        // 重新加载用户列表
        await loadUsers()
      } else {
        Modal.error({
          title: '失败',
          content: response.message || '角色分配失败'
        })
      }
    } catch (error) {
      console.error('角色分配失败:', error)
      Modal.error({
        title: '失败',
        content: '角色分配失败'
      })
    } finally {
      setRoleLoading(false)
    }
  }

  // 关闭角色分配模态框
  const handleRoleModalCancel = () => {
    setRoleModalVisible(false)
    setSelectedUser(null)
    setSelectedRoleIds([])
    setRoleTableData([])
    setRoleTablePagination({ current: 1, pageSize: 10, total: 0 })
    setRoleSearchParams({})
  }

  // 角色表格行选择配置
  const roleRowSelection = {
    selectedRowKeys: selectedRoleIds,
    onChange: (selectedRowKeys: React.Key[]) => {
      const newSelectedRoleIds = selectedRowKeys.map(key => Number(key))
      setSelectedRoleIds(newSelectedRoleIds)
    },
    onSelectAll: (selected: boolean, selectedRows: Role[], changeRows: Role[]) => {
      console.log('角色全选状态:', selected, '选中行:', selectedRows, '变化行:', changeRows)
    },
    onSelect: (record: Role, selected: boolean, selectedRows: Role[]) => {
      console.log('角色单选状态:', record, selected, '已选行:', selectedRows)
    },
    getCheckboxProps: (record: Role) => ({
      disabled: record.status === 0, // 禁用已禁用的角色
      name: record.roleName,
    }),
  }

  // 表格筛选和排序处理
  const handleTableChange = (_pagination: any, filters: any, sorter: any) => {
    setFilteredInfo(filters)
    setSortedInfo(sorter)
  }

  // 清除筛选
  const clearFilters = () => {
    setFilteredInfo({})
    setSortedInfo({})
  }

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(selectedRowKeys)
    },
    onSelectAll: (selected: boolean, selectedRows: User[], changeRows: User[]) => {
      console.log('全选状态:', selected, '选中行:', selectedRows, '变化行:', changeRows)
    },
    onSelect: (record: User, selected: boolean, selectedRows: User[]) => {
      console.log('单选状态:', record, selected, '已选行:', selectedRows)
    },
    getCheckboxProps: (record: User) => ({
      disabled: record.userName === 'admin', // 禁用admin用户的选择
      name: record.userName,
    }),
  }

  // 批量删除用户
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的用户')
      return
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可恢复。`,
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        setTableLoading(true)
        try {
          // 这里可以调用批量删除API
          for (const userId of selectedRowKeys) {
            await dispatch(deleteUser(userId as number) as any).unwrap()
          }
          message.success(`成功删除 ${selectedRowKeys.length} 个用户`)
          setSelectedRowKeys([])
          await loadUsers()
        } catch (error) {
          message.error('批量删除失败')
        } finally {
          setTableLoading(false)
        }
      }
    })
  }

  // 批量启用/禁用用户
  const handleBatchStatusChange = (status: number) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的用户')
      return
    }

    const statusText = status === 1 ? '启用' : '禁用'
    Modal.confirm({
      title: `批量${statusText}确认`,
      content: `确定要${statusText}选中的 ${selectedRowKeys.length} 个用户吗？`,
      okText: `确定${statusText}`,
      cancelText: '取消',
      onOk: async () => {
        setTableLoading(true)
        try {
          // 这里可以调用批量更新状态API
          for (const userId of selectedRowKeys) {
            await dispatch(updateUser({ 
              id: userId as number, 
              userData: { status } 
            }) as any).unwrap()
          }
          message.success(`成功${statusText} ${selectedRowKeys.length} 个用户`)
          setSelectedRowKeys([])
          await loadUsers()
        } catch (error) {
          message.error(`批量${statusText}失败`)
        } finally {
          setTableLoading(false)
        }
      }
    })
  }

  // 导出选中数据
  const handleExportSelected = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要导出的用户')
      return
    }

    const selectedUsers = users.filter(user => selectedRowKeys.includes(user.id))
    const csvContent = [
      ['ID', '用户名', '真实姓名', '邮箱', '手机号', '状态', '创建时间'],
      ...selectedUsers.map(user => [
        user.id,
        user.userName,
        user.realName || '',
        user.email || '',
        user.phone || '',
        user.status === 1 ? '启用' : '禁用',
        user.createTime ? new Date(user.createTime).toLocaleString() : ''
      ])
    ].map(row => row.join(',')).join('\n')

    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `用户数据_${new Date().toISOString().split('T')[0]}.csv`
    link.click()
    URL.revokeObjectURL(link.href)
    message.success(`已导出 ${selectedRowKeys.length} 条用户数据`)
  }

  // 角色表格列定义
  const roleColumns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
      render: (remark: string) => remark || '-',
    },
  ]

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      sorter: (a: User, b: User) => a.id - b.id,
      sortOrder: sortedInfo.columnKey === 'id' ? sortedInfo.order : null,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      filteredValue: filteredInfo.userName || null,
      onFilter: (value: any, record: User) => 
        record.userName.toLowerCase().includes(value.toString().toLowerCase()),
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: any) => (
        <div style={{ padding: 8 }}>
          <Input
            placeholder="搜索用户名"
            value={selectedKeys[0]}
            onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={() => confirm()}
            style={{ marginBottom: 8, display: 'block' }}
          />
          <Space>
            <Button
              type="primary"
              onClick={() => confirm()}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
            <Button
              onClick={() => clearFilters && clearFilters()}
              size="small"
              style={{ width: 90 }}
            >
              重置
            </Button>
          </Space>
        </div>
      ),
      filterIcon: (filtered: boolean) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
      sorter: (a: User, b: User) => a.userName.localeCompare(b.userName),
      sortOrder: sortedInfo.columnKey === 'userName' ? sortedInfo.order : null,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      filteredValue: filteredInfo.realName || null,
      onFilter: (value: any, record: User) => 
        (record.realName || '').toLowerCase().includes(value.toString().toLowerCase()),
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: any) => (
        <div style={{ padding: 8 }}>
          <Input
            placeholder="搜索真实姓名"
            value={selectedKeys[0]}
            onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={() => confirm()}
            style={{ marginBottom: 8, display: 'block' }}
          />
          <Space>
            <Button
              type="primary"
              onClick={() => confirm()}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
            <Button
              onClick={() => clearFilters && clearFilters()}
              size="small"
              style={{ width: 90 }}
            >
              重置
            </Button>
          </Space>
        </div>
      ),
      filterIcon: (filtered: boolean) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
      sorter: (a: User, b: User) => (a.realName || '').localeCompare(b.realName || ''),
      sortOrder: sortedInfo.columnKey === 'realName' ? sortedInfo.order : null,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      filteredValue: filteredInfo.email || null,
      onFilter: (value: any, record: User) => 
        (record.email || '').toLowerCase().includes(value.toString().toLowerCase()),
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: any) => (
        <div style={{ padding: 8 }}>
          <Input
            placeholder="搜索邮箱"
            value={selectedKeys[0]}
            onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={() => confirm()}
            style={{ marginBottom: 8, display: 'block' }}
          />
          <Space>
            <Button
              type="primary"
              onClick={() => confirm()}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
            <Button
              onClick={() => clearFilters && clearFilters()}
              size="small"
              style={{ width: 90 }}
            >
              重置
            </Button>
          </Space>
        </div>
      ),
      filterIcon: (filtered: boolean) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      filteredValue: filteredInfo.phone || null,
      onFilter: (value: any, record: User) => 
        (record.phone || '').includes(value.toString()),
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: any) => (
        <div style={{ padding: 8 }}>
          <Input
            placeholder="搜索手机号"
            value={selectedKeys[0]}
            onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={() => confirm()}
            style={{ marginBottom: 8, display: 'block' }}
          />
          <Space>
            <Button
              type="primary"
              onClick={() => confirm()}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
            <Button
              onClick={() => clearFilters && clearFilters()}
              size="small"
              style={{ width: 90 }}
            >
              重置
            </Button>
          </Space>
        </div>
      ),
      filterIcon: (filtered: boolean) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '启用', value: 1 },
        { text: '禁用', value: 0 },
      ],
      filteredValue: filteredInfo.status || null,
      onFilter: (value: any, record: User) => record.status === value,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'} icon={status === 1 ? <CheckCircleOutlined /> : <CloseCircleOutlined />}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
      sorter: (a: User, b: User) => {
        const timeA = a.createTime ? new Date(a.createTime).getTime() : 0
        const timeB = b.createTime ? new Date(b.createTime).getTime() : 0
        return timeA - timeB
      },
      sortOrder: sortedInfo.columnKey === 'createTime' ? sortedInfo.order : null,
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      render: (_: unknown, record: User) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => showUserModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<TeamOutlined />}
            onClick={() => showRoleModal(record)}
          >
            分配角色
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleUserDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              size="small" 
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className={styles.userManagement}>
      <Card>
        {/* 搜索表单 */}
        <Form<UserQuery>
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          className={styles.searchForm}
        >
          <Form.Item name="userName">
            <Input id="search-userName" placeholder="用户名" style = {{width: 120}} />
          </Form.Item>
          <Form.Item name="realName">
            <Input id="search-realName" placeholder="真实姓名" style = {{width: 120}} />
          </Form.Item>
          <Form.Item name="email">
            <Input id="search-email" placeholder="邮箱" />
          </Form.Item>
          <Form.Item name="status">
            <Select id="search-status" placeholder="状态" allowClear style={{ width: 120 }}>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 操作按钮 */}
        <div className={styles.tableActions}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />}
                  onClick={() => showUserModal()}
                >
                  新增用户
                </Button>
                
                {selectedRowKeys.length > 0 && (
                  <>
                    <Dropdown
                      overlay={
                        <Menu>
                          <Menu.Item 
                            key="enable" 
                            icon={<CheckCircleOutlined />}
                            onClick={() => handleBatchStatusChange(1)}
                          >
                            批量启用
                          </Menu.Item>
                          <Menu.Item 
                            key="disable" 
                            icon={<CloseCircleOutlined />}
                            onClick={() => handleBatchStatusChange(0)}
                          >
                            批量禁用
                          </Menu.Item>
                          <Menu.Divider />
                          <Menu.Item 
                            key="export" 
                            icon={<ExportOutlined />}
                            onClick={handleExportSelected}
                          >
                            导出选中
                          </Menu.Item>
                          <Menu.Divider />
                          <Menu.Item 
                            key="delete" 
                            icon={<DeleteOutlined />}
                            onClick={handleBatchDelete}
                            danger
                          >
                            批量删除
                          </Menu.Item>
                        </Menu>
                      }
                    >
                      <Button>
                        批量操作 ({selectedRowKeys.length}) <DownOutlined />
                      </Button>
                    </Dropdown>
                  </>
                )}
              </Space>
            </Col>
            
            <Col>
              <Space>
                <Tooltip title="清除所有筛选条件">
                  <Button 
                    icon={<ClearOutlined />}
                    onClick={clearFilters}
                    disabled={Object.keys(filteredInfo).length === 0 && Object.keys(sortedInfo).length === 0}
                  >
                    清除筛选
                  </Button>
                </Tooltip>
                
                <Tooltip title="刷新表格数据">
                  <Button 
                    icon={<ReloadOutlined />}
                    onClick={() => loadUsers()}
                    loading={loading}
                  >
                    刷新
                  </Button>
                </Tooltip>
              </Space>
            </Col>
          </Row>
          
          {selectedRowKeys.length > 0 && (
            <div style={{ 
              marginTop: 12, 
              padding: '8px 12px', 
              background: '#e6f7ff', 
              borderRadius: '6px',
              border: '1px solid #91d5ff'
            }}>
              <Space>
                <Text style={{ color: '#0050b3' }}>
                  已选择 <strong>{selectedRowKeys.length}</strong> 项
                </Text>
                <Button 
                  type="link" 
                  size="small"
                  onClick={() => setSelectedRowKeys([])}
                >
                  取消选择
                </Button>
              </Space>
            </div>
          )}
        </div>

        {/* 用户表格 */}
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading || tableLoading}
          rowSelection={rowSelection}
          onChange={handleTableChange}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              const newPagination = { 
                current: page, 
                pageSize: pageSize || 10, 
                total: pagination.total 
              }
              setPagination(newPagination)
              
              // 使用新的分页参数加载数据
              const queryParams = {
                pageIndex: page,
                pageSize: pageSize || 10,
                ...searchForm.getFieldsValue(),
              }
              
              dispatch(getUserList(queryParams) as any)
            },
          }}
          scroll={{ x: 1200 }}
          size="middle"
        />
      </Card>

      {/* 用户编辑模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={isModalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width={600}
      >
        <Form<Partial<User>>
          form={userForm}
          layout="vertical"
          onFinish={handleUserSave}
        >
          <Form.Item
            name="userName"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' }
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码至少6个字符' }
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item
            name="realName"
            label="真实姓名"
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea placeholder="请输入备注" rows={3} />
          </Form.Item>

          <Form.Item
            name="roleIds"
            label="角色"
          >
            <Select
              mode="multiple"
              placeholder="请选择角色"
              allowClear
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.roleName}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item className={styles.modalActions}>
            <Space>
              <Button onClick={handleModalCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 角色分配模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar icon={<TeamOutlined />} style={{ backgroundColor: '#1890ff' }} />
            <div>
              <div style={{ fontSize: '16px', fontWeight: 'bold' }}>分配角色</div>
              <div style={{ fontSize: '12px', color: '#666', fontWeight: 'normal' }}>
                为 {selectedUser?.realName || selectedUser?.userName} 分配系统角色
              </div>
            </div>
          </div>
        }
        open={roleModalVisible}
        onOk={handleRoleSave}
        onCancel={handleRoleModalCancel}
        confirmLoading={roleLoading}
        width={900}
        okText="确定"
        cancelText="取消"
        style={{ top: 20 }}
      >
        {/* 用户信息卡片 */}
        <div style={{ 
          background: '#f6f8fa', 
          padding: '16px', 
          borderRadius: '8px', 
          marginBottom: '20px',
          border: '1px solid #e1e4e8'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar 
              size={48} 
              icon={<UserOutlined />} 
              style={{ backgroundColor: '#52c41a' }}
            />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#24292e' }}>
                {selectedUser?.realName || selectedUser?.userName}
              </div>
              <div style={{ fontSize: '14px', color: '#586069' }}>
                用户名：{selectedUser?.userName}
              </div>
              {selectedUser?.email && (
                <div style={{ fontSize: '12px', color: '#586069' }}>
                  邮箱：{selectedUser.email}
                </div>
              )}
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: '12px', color: '#666' }}>已选择角色</div>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {selectedRoleIds.length}
              </div>
            </div>
          </div>
        </div>

        <Divider orientation="left" style={{ fontSize: '14px', fontWeight: 'bold' }}>
          <SafetyOutlined style={{ marginRight: 8 }} />
          角色权限选择
        </Divider>

        {/* 角色搜索栏 */}
        <div style={{ marginBottom: 16 }}>
          <Input
            placeholder="搜索角色名称或编码"
            prefix={<SearchOutlined />}
            allowClear
            value={roleSearchParams.roleName}
            onChange={(e) => {
              const searchValue = e.target.value
              const newParams = { roleName: searchValue || undefined }
              setRoleSearchParams(newParams)
              debouncedRoleSearch(newParams)
            }}
            style={{ marginBottom: 12 }}
          />
        </div>

        {/* 角色表格 */}
        <div style={{ marginBottom: 16 }}>
          <Table
            columns={roleColumns}
            dataSource={roleTableData}
            rowKey="id"
            loading={roleTableLoading}
            rowSelection={roleRowSelection}
            pagination={{
              current: roleTablePagination.current,
              pageSize: roleTablePagination.pageSize,
              total: roleTablePagination.total,
              showSizeChanger: false,
              showQuickJumper: false,
              showTotal: (total) => `共 ${total} 条角色`,
              pageSizeOptions: ['10'],
              onChange: (page, pageSize) => {
                setRoleTablePagination({
                  current: page,
                  pageSize: pageSize || 10,
                  total: roleTablePagination.total
                })
              },
            }}
            scroll={{ y: 300 }}
            size="small"
          />
        </div>

        {/* 选择总结 */}
        {selectedRoleIds.length > 0 && (
          <div style={{ 
            padding: '12px', 
            background: '#e6f7ff', 
            borderRadius: '6px',
            border: '1px solid #91d5ff'
          }}>
            <div style={{ fontWeight: 'bold', marginBottom: 8, color: '#0050b3' }}>
              已选择 {selectedRoleIds.length} 个角色：
            </div>
            <div style={{ maxHeight: '60px', overflowY: 'auto' }}>
              {selectedRoleIds.map(roleId => {
                const role = roles.find(r => r.id === roleId)
                return role ? (
                  <Tag key={roleId} color="blue" style={{ marginBottom: 4, marginRight: 4 }}>
                    {role.roleName}
                  </Tag>
                ) : null
              })}
            </div>
          </div>
        )}
      </Modal>
    </div>
  )
}

export default UserManagement